//
//  RCNearbyDiscountVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-7-17.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCNearbyDiscountVC.h"
#import "RCDiscountDataModel.h"
#import "RCSelectorView.h"
#import "MileSeletor.h"
#import "RCDiscountDetailCell.h"
#import "RCMerchantDetailVC.h"
#import "GloableEngineService.h"
#import "IManager+ModuleSearchCityCategory.h"
#import "RCSearchAllCityDataModel.h"
#import "RCCategoryView.h"
#import "RCSearchAllCityDataModel.h"
#import "UIColor-Expanded.h"
#import "NSString+NSString_Ex_.h"
#import "CommonDefines.h"
#import "MBProgressHUD.h"
#import "NSArray+EX.h"

#define kRCCategoryView_Distrcit 80
#define kRCCategoryView_Category 81
#define kBottomImageFile           @"image_merchant_street.png"


@interface RCNearbyDiscountVC ()<IManagerDelegate,RCSeletorViewDelegate,MileSeletorDelegate,RCSubViewTablelistProtocol,RCCategoryViewProtocol,MBProgressHUDDelegate>{
    
    
    KMerchantListType       _vcType;             //VC的类型
    int64_t                 _districtReqID, _merchantTypeReqID, _listReqID;
    
    RCDiscountDataModel *_dataModel;
    RCSearchAllCityDataModel *_districtDataModel, *_categoryDataModel; //商区 和 类型的数据模型
    
    BOOL                     isRefresh;
    
    
    RCSelectorView           *_selectorView;
    
    //请求参数
    NSInteger                _reqMerchantDistance;  //商户距离
    NSString                 *_reqDistrictTypeString; //商区类型字面字符串
    NSString                 *_reqDistrictType;      //商区类型id
    NSString                 *_reqMerchantType;      //商户类型id
    NSString                 *_reqMerchantTypeString; //商户类型字面字符串
    kMerchantsSortedType     _reqSortedType;        //排序类型
    
    NSArray                 *_distanceArray;
    NSDictionary            *_merchantTypeDic;
    NSArray                 *_sortedArray;
    
    NSInteger               _pn;
    
}
@property (nonatomic, retain) RCDiscountDataModel *dataModel;
@property (nonatomic, retain) RCSearchAllCityDataModel *categoryDataModel;
@property (nonatomic, retain) RCSearchAllCityDataModel *districtDataModel;
@property (nonatomic, assign) NSString *reqMerchantType;
@property (nonatomic, retain) NSString *reqDistrictType;
@property (nonatomic, retain) NSString *reqDistrictTypeString;
@property (nonatomic, retain) NSString *reqMerchantTypeString;
@property (nonatomic, retain) MBProgressHUDEx *progressHub;

@end

@implementation RCNearbyDiscountVC

@synthesize dataModel = _dataModel;
@synthesize categoryDataModel = _categoryDataModel;
@synthesize districtDataModel = _districtDataModel;
@synthesize vcType            = _vcType;
@synthesize reqMerchantType   = _reqMerchantType;
@synthesize reqDistrictType   = _reqDistrictType;
@synthesize reqMerchantTypeString = _reqMerchantTypeString;
@synthesize reqDistrictTypeString = _reqDistrictTypeString;
@synthesize progressHub = _progressHub;


- (id) initWithDiscountType:(NSString *)merchantType withDiscountID:(NSString *)subTypeID
{
    self = [super init];
    if (self) {
        _vcType = KMerchantListType_Discount;
        
        _reqMerchantDistance = 0; //默认1000m
        _reqSortedType       = kSortedType_Default;
        
        _reqMerchantTypeString=[merchantType retain];
        
        if (subTypeID == nil) {
            _reqMerchantType     = [merchantType retain];
        }else{
            _reqMerchantType     = [subTypeID retain];
        }
        
        
        _distanceArray = [[NSArray alloc] initWithObjects:@"1km",@"5km",@"10km",@"不限距离", nil];
        _sortedArray   = [[NSArray alloc] initWithObjects:@"默认排序",@"按距离排序", nil];
        
    }
    return self;
}




- (void) dealloc
{
    
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_districtReqID];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_merchantTypeReqID];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_listReqID];
    
    [_reqDistrictTypeString release];
    [_reqMerchantTypeString release];
    [_reqDistrictType release];
    [_reqMerchantType release];
    [_districtDataModel release];
    [_categoryDataModel release];
    [_merchantTypeDic   release];
    [_distanceArray     release];
    [_sortedArray       release];
    [_reqMerchantType   release];
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    [super dealloc];
    
}


- (void)viewDidLoad
{
    
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    
    [self refreshData];
    [self getTypeCatogory];
    if (_vcType == KMerchantListType_District) {
        [self getDistcitTag];
    }
    
    NSArray *titleArray = nil;
    if (_vcType == KMerchantListType_Distance || _vcType == KMerchantListType_Discount)
        titleArray = [NSArray arrayWithObjects:@"不限距离",self.reqMerchantTypeString,@"默认排序", nil];
    else
        titleArray = [NSArray arrayWithObjects:self.reqDistrictTypeString,self.reqMerchantTypeString,@"默认排序", nil];
    
    _selectorView = [[RCSelectorView alloc] initWithFrame:CGRectMake(0, 0, 320, 50) titleArray:titleArray];
    _selectorView.delegate = self;
    [self.view addSubview:_selectorView];
    [_selectorView setBackgroundColor:[UIColor clearColor]];
    [_selectorView release];
    
    
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y+50,baseVCTableView.frame.size.width,baseVCTableView.frame.size.height-self.navigationController.navigationBar.frame.size.height-4);
        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
        [self addPullRefresh];
    }
    if (![NSString stringIsNullOrEmpty:[GloableEngineService sharedInstance].userSelectStreetName]) {
        UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, UIScreenHeight-64-30, 320, 30)];
        bottomView.backgroundColor = [UIColor colorWithHex:0xff442709];
        
        UIImageView *bottomImageView = [[UIImageView alloc]initWithFrame:CGRectMake(14, 10, 10, 10)];
        bottomImageView.backgroundColor = [UIColor clearColor];
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kBottomImageFile];
        [bottomImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
        [bottomView addSubview:bottomImageView];
        [bottomImageView release];
        
        UILabel *bottomLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 9, 200, 12)];
        bottomLabel.backgroundColor = [UIColor clearColor];
        bottomLabel.textColor = [UIColor whiteColor];
        bottomLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
        bottomLabel.text = [GloableEngineService sharedInstance].userSelectStreetName;
        [bottomView addSubview:bottomLabel];
        [bottomLabel release];
        
        [self.viewContainer addSubview:bottomView];
        [bottomView release];
        
        CGRect tableViewNewFrame = baseVCTableView.frame;
        tableViewNewFrame.size.height -= 30;
        baseVCTableView.frame = tableViewNewFrame;
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma
#pragma mark Get Category Or District Tags

- (void) getTypeCatogory
{
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    _merchantTypeReqID = [[IManager sharedInstance]requestSearchCityCategory:cityID withDelegate:self];
}

- (void) getDistcitTag
{
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    _districtReqID =  [[IManager sharedInstance]requestSearchCityDistrict:cityID withDelegate:self];
}


#pragma
#pragma mark IManage Delegate
-(void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    
    if ([dataModel isKindOfClass:[RCDiscountDataModel class]]) {
        
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        if (isRefresh) {
            //下拉刷新
            self.dataModel = (RCDiscountDataModel *)dataModel;
            [self finishRefreshingData];
        }else{
            //加载更多的
            RCDiscountDataModel *newData = (RCDiscountDataModel *)dataModel;
            self.dataModel.currentOffset = newData.currentOffset;
            self.dataModel.currentReturnNum = newData.currentReturnNum;
            self.dataModel.totalCount = newData.totalCount;
            [self.dataModel.itemArray addObjectsFromArray:newData.itemArray];
            [self finishLoadMoreData];
            [baseVCTableView reloadData];
        }
        
        [self  performSelector:@selector(setBarTitle) withObject:nil afterDelay:0.5];
        
        
        NSInteger currentTotal = [self.dataModel.itemArray count];
        _pn = currentTotal;
        if (currentTotal < self.dataModel.totalCount) {
            [self addPullLoadMore];
        }else{
            [self noMoreData];
        }
    }else{
        //category分类数据
        RCSearchAllCityDataModel *tagsModel = (RCSearchAllCityDataModel*)dataModel;
        
        if (_districtReqID == requestId) {
            self.districtDataModel = tagsModel;
        }else{
            self.categoryDataModel = tagsModel;
        }
    }
    
}

- (void) setBarTitle
{
    self.titleLabelText = [NSString stringWithFormat:@"附近优惠[共%d家]",self.dataModel.totalCount];
    self.navigationItem.titleView = [self createTitleView];
}

-(void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_listReqID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        if (isRefresh) {
            //下拉刷新
            
            [self finishRefreshingData];
        }else{
            //加载更多的
            [self finishLoadMoreData];
        }
    }
}


-(void) loadMoreData
{
    isRefresh = NO;
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    NSString *page = [NSString stringWithFormat:@"%d",_pn];
    _listReqID = [[IManager sharedInstance]requestNearbyMerchantsType:_reqMerchantType inDistance:_reqMerchantDistance withSoretedType:_reqSortedType forPage:page withRn:@"10" inCity:cityID withMerchantsListType:self.vcType withDistrictID:nil withDelegate:self];
    
    
    
}

#pragma
#pragma mark ServerData ----下拉刷新数据

-(void) refreshData
{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    isRefresh = YES;
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    
    _pn = 0;
    if (self.vcType == KMerchantListType_Distance) {
        _listReqID = [[IManager sharedInstance]requestNearbyMerchantsType:_reqMerchantType inDistance:_reqMerchantDistance withSoretedType:_reqSortedType forPage:@"0" withRn:@"10" inCity:cityID withMerchantsListType:self.vcType withDistrictID:nil withDelegate:self];
    }else if (self.vcType == KMerchantListType_District){
        _listReqID = [[IManager sharedInstance]requestNearbyMerchantsType:_reqMerchantType inDistance:_reqMerchantDistance withSoretedType:_reqSortedType forPage:@"0" withRn:@"10" inCity:cityID withMerchantsListType:self.vcType withDistrictID:self.reqDistrictType withDelegate:self];
    }else{
        _listReqID = [[IManager sharedInstance] requestNearbyDiscountsType:_reqMerchantType inDistance:_reqMerchantDistance withSoretedType:_reqSortedType forPage:@"0" withRn:@"10" inCity:cityID withDelegate:self];
        //        _listReqID = [[IManager sharedInstance]requestNearbyMerchantsType:_reqMerchantType inDistance:_reqMerchantDistance withSoretedType:_reqSortedType forPage:@"0" withRn:@"10" inCity:cityID withMerchantsListType:self.vcType withDistrictID:self.reqDistrictType withDelegate:self];
    }
}



#pragma
#pragma mark SubView Delegate Start


#pragma mark SubView Delegate------SubViews

-(UIView *)viewForSelectorIndex:(NSInteger)index
{
    if (index == 0) {
        if (_vcType == KMerchantListType_Distance || _vcType == KMerchantListType_Discount) {
            MileSeletor  *_mileSeletorView = [[[MileSeletor alloc] initWithFrame:CGRectMake(0, 0, 320, 50) andDataSource:_distanceArray] autorelease];
            _mileSeletorView.delegate = self;
            [_mileSeletorView setBackgroundColor:[UIColor whiteColor]];
            return _mileSeletorView;
        }else{
            RCCategoryView *districtView = [[RCCategoryView alloc] initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-20-44-50) andDataSource:self.districtDataModel];
            districtView.delegate = self;
            districtView.tag = kRCCategoryView_Distrcit;
            return districtView;
        }
        
    }else if (index == 1) {
        RCCategoryView *categoryView = [[RCCategoryView alloc] initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-20-44-50) andDataSource:self.categoryDataModel];
        categoryView.delegate = self;
        categoryView.tag = kRCCategoryView_Category;
        return categoryView;
    }else {
        RCSubViewTablelist *v = [[[RCSubViewTablelist alloc]
                                  initWithFrame:CGRectMake(0, 0, 320, 80)
                                  andTitles:_sortedArray] autorelease];
        v.delegate = self;
        return v;
    }
}



#pragma mark SubView Delegate------SubView Delegate  1

- (void) didSelectMileSeletorAtIndex:(NSInteger)index
{
    NSString *distance = [_distanceArray objectAtIndex:index];
    [_selectorView changeCurrentTabbarTitle:distance];
    [_selectorView selectorHide];
    
    NSRange kmRang = [distance rangeOfString:@"km"];
    NSRange rang;
    NSRange noLimitRange;
    if (kmRang.location == NSNotFound) {
        rang = [distance rangeOfString:@"m"];
        if (rang.location != NSNotFound) {
            _reqMerchantDistance = [[distance substringToIndex:rang.location] intValue];
            [self refreshData];
            return;
        }
        
        noLimitRange = [distance rangeOfString:@"不限距离"];
        if (noLimitRange.location != NSNotFound) {
            _reqMerchantDistance = 0;
            [self refreshData];
        }
        
        
    }else{
        _reqMerchantDistance = [[distance substringToIndex:kmRang.location] intValue]*1000;
        [self refreshData];
    }
    
    
}


#pragma mark SubView Delegate------SubView Delegate  2
- (void) rcCategoryView:(RCCategoryView *)rcCategoryView didSelectCategory:(NSString *)category withItem:(RCSearchAllCityItem *)item
{
    [_selectorView changeCurrentTabbarTitle:item.itemName];
    [_selectorView selectorHide];
    
    if (rcCategoryView.tag == kRCCategoryView_Category) {
        self.reqMerchantType  = item.itemID;
    }else if (rcCategoryView.tag == kRCCategoryView_Distrcit){
        
    }
    [self refreshData];
    
}




#pragma mark SubView Delegate------SubView Delegate  3

- (void) rcSubViewTablelist:(RCSubViewTablelist *)rcSubViewTablelist didSelectTitle:(NSString *)titleTag atIndex:(NSInteger)index
{
    [_selectorView changeCurrentTabbarTitle:titleTag];
    [_selectorView selectorHide];
    
    _reqSortedType = index;
    
    [self refreshData];
}


#pragma mark SubView Delegate End



#pragma
#pragma mark TableView DataSource & Delegate

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataModel.itemArray count];
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"UITableViewDiscountCell";
    RCDiscountDetailCell *discountCell = (RCDiscountDetailCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (nil == discountCell) {
        discountCell = [[[RCDiscountDetailCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier] autorelease];
        discountCell.accessoryType = UITableViewCellAccessoryNone;
        discountCell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    RCDiscountDetail *itemInfo = [self.dataModel.itemArray safeObjectAtIndex:[indexPath row]];
    if (nil == itemInfo) {
        return nil;
    }
    [discountCell setContentWithData:itemInfo];
    
    return discountCell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    RCDiscountDetail *itemInfo = [self.dataModel.itemArray safeObjectAtIndex:[indexPath row]];
    if (nil == itemInfo) {
        return;
    }
    RCMerchantDetailVC *vc = [[RCMerchantDetailVC alloc]initWithMerchantID:itemInfo.itemID];
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];

}
@end
